package io.renren.modules.bs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DeleteFileUtil;
import io.renren.common.utils.MathUtil;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.app.dto.DischargeRegistrationDto;
import io.renren.modules.app.dto.PatientDto;
import io.renren.modules.app.dto.WardRoundReportDto;
import io.renren.modules.app.utils.GetUrlPic;
import io.renren.modules.app.vo.AllReportVo;
import io.renren.modules.app.vo.BsDepartmentPatientVo;
import io.renren.modules.app.vo.ReportVo;
import io.renren.modules.bs.dao.BsPatientDao;
import io.renren.modules.bs.dto.ExtraDto;
import io.renren.modules.bs.entity.*;
import io.renren.modules.bs.service.*;
import io.renren.modules.bs.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service("bsPatientService")
public class BsPatientServiceImpl extends ServiceImpl<BsPatientDao, BsPatientEntity> implements BsPatientService {

    @Value("${file.path}")
    private String filePath;

    @Autowired
    private BsHospitalService hospitalService;

    @Autowired
    private BsDepartmentService departmentService;

    @Autowired
    private BsDepartmentPatientService departmentPatientService;

    @Autowired
    private BsExtractRecordService extractRecordService;

    @Autowired
    private BsExtractRecordDetailService extractRecordDetailService;

    @Autowired
    private BsExtractDetailPatientService extractDetailPatientService;

    @Autowired
    private BsDepartmentPatientImgService patientImgService;

    @Autowired
    private BsPatientService patientService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BsPatientEntity> bsPatientEntityQueryWrapper = new QueryWrapper<>();
        String patientName = (String) params.get("patientName");
        if (StringUtils.isNotEmpty(patientName)) {
            bsPatientEntityQueryWrapper.like("patient_name", patientName);
        }
        IPage<BsPatientEntity> page = this.page(
                new Query<BsPatientEntity>().getPage(params),
                bsPatientEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<PatientOptionVo> getOptionsByName(String patientName) {

        List<PatientOptionVo> patientOptionVos = new ArrayList<>();
        List<PatientVo> patientVos = this.baseMapper.getOnlineListByName(patientName);
        Set<Long> departmentIdSet = patientVos.stream().map(PatientVo::getDepartmentId).collect(Collectors.toSet());
        if (departmentIdSet.size() > 0) {

            Collection<BsDepartmentEntity> bsDepartmentEntities = this.departmentService.listByIds(departmentIdSet);
            Set<Long> hospitalIdSet = bsDepartmentEntities.stream().map(BsDepartmentEntity::getHospitalId).collect(Collectors.toSet());
            if (hospitalIdSet.size() > 0) {

                Map<Long, List<PatientVo>> patientMap = patientVos.stream().collect(Collectors.groupingBy(PatientVo::getDepartmentId));

                Collection<BsHospitalEntity> bsHospitalEntities = this.hospitalService.listByIds(hospitalIdSet);
                Map<Long, List<BsDepartmentEntity>> departMap = bsDepartmentEntities.stream().collect(Collectors.groupingBy(BsDepartmentEntity::getHospitalId));
                Map<Long, Long> maps = bsDepartmentEntities.stream().collect(Collectors.toMap(BsDepartmentEntity::getDepartmentId, BsDepartmentEntity::getHospitalId, (key1, key2) -> key2));
                for (BsHospitalEntity hospitalEntity : bsHospitalEntities) {
                    PatientOptionVo patientOptionVo = new PatientOptionVo();
                    patientOptionVo.setHospitalName(hospitalEntity.getHospitalName());
                    List<BsDepartmentEntity> bsDepartmentEntityList = departMap.get(hospitalEntity.getHospitalId());
                    for (BsDepartmentEntity departmentEntity : bsDepartmentEntityList) {
                        List<PatientVo> patientVoList = patientMap.get(departmentEntity.getDepartmentId());
                        for (PatientVo patientVo : patientVoList) {
                            patientVo.setDepartmentName(departmentEntity.getDepartmentName());
                        }
                        patientOptionVo.setOptions(patientVoList);
                    }

                    patientOptionVos.add(patientOptionVo);
                }
            }
        }
        return patientOptionVos;
    }

    @Override
    public Integer getExtractableNumber(Integer extraType, Long dataValue) {
        if (extraType == 1) {
            //医院
            return this.hospitalService.getExtractableNumber(dataValue);
        } else {
            //科室
            return this.departmentService.getExtractableNumber(dataValue);
        }
    }

    @Override
    public List<TreeVo> getTreeData(Integer level, String joinId) {


        List<TreeVo> treeVos = new ArrayList<>();

        if (level == 0) {
            //医院
            List<BsHospitalVo> hospitalVoList = this.hospitalService.getTreeData();
            for (BsHospitalVo hospitalVo : hospitalVoList) {
                TreeVo treeVo = new TreeVo();
                treeVo.setId(hospitalVo.getHospitalId() + "");
                treeVo.setLeaf(false);
                treeVo.setName(hospitalVo.getHospitalName());
                treeVo.setAvailableNumber(hospitalVo.getAvailableNumber());
                treeVos.add(treeVo);
            }
        } else if (level == 1) {

            List<BsDepartmentTreeVo> departmentTreeVoList = this.departmentService.getTreeData(Long.parseLong(joinId));
            for (BsDepartmentTreeVo departmentTreeVo : departmentTreeVoList) {
                TreeVo treeVo = new TreeVo();
                treeVo.setId(joinId + "-" + departmentTreeVo.getDepartmentId());
                treeVo.setLeaf(false);
                treeVo.setName(departmentTreeVo.getDepartmentName());
                treeVo.setAvailableNumber(departmentTreeVo.getAvailableNumber());
                treeVos.add(treeVo);
            }
        } else {
            String[] split = joinId.split("-");
            List<BsPatientTreeVo> bsPatientTreeVoList = this.baseMapper.getTreeData(Long.parseLong(split[1]));
            for (BsPatientTreeVo patientTreeVo : bsPatientTreeVoList) {
                TreeVo treeVo = new TreeVo();
                treeVo.setId(joinId + "-" + patientTreeVo.getDepartmentPatientId());
                treeVo.setLeaf(true);
                treeVo.setName(patientTreeVo.getPatientName());
                treeVo.setAvailableNumber(patientTreeVo.getAvailableNumber());
                treeVo.setExtraNumber(1);
                treeVos.add(treeVo);
            }
        }
        return treeVos;
    }

    @Override
    @Transactional
    public List<ExtraPatientVo> extra(List<ExtraDto> extraDtos) {

        BsExtractRecordEntity bsExtractRecordEntity = new BsExtractRecordEntity();
        bsExtractRecordEntity.setExtractType(2);
        bsExtractRecordEntity.setIsDone(0);
        boolean save = this.extractRecordService.save(bsExtractRecordEntity);
        if (!save) {
            throw new RuntimeException("抽取记录保存失败");
        }
        //以医院为单位抽取
        for (ExtraDto extraDto : extraDtos) {
            String joinId = extraDto.getJoinId();
            String[] split = joinId.split("-");
            extraDto.setHospitalId(Long.parseLong(split[0]));
            if (split.length > 1) {
                extraDto.setDepartmentId(Long.parseLong(split[1]));
            }
            if (split.length > 2) {
                extraDto.setPatientId(Long.parseLong(split[2]));
            }
        }
        //开始保存详情
        Map<Long, List<ExtraDto>> extraDtpMap = extraDtos.stream().collect(Collectors.groupingBy(ExtraDto::getHospitalId));
        List<ExtraHospResultVo> extraHospResultVos = new ArrayList<>();
        for (Map.Entry<Long, List<ExtraDto>> entry : extraDtpMap.entrySet()) {
            ExtraHospResultVo extraHospResultVo = new ExtraHospResultVo();
            List<ExtraDeptRestVo> extraDeptRestVos = new ArrayList<>();
            //同一医院
            List<ExtraDto> extraDtoList = entry.getValue();
            Integer num = null;
            List<ExtraDto> newExtraDtoList = new ArrayList<>();
            for (ExtraDto extraDto : extraDtoList) {
                //抽取
                if (extraDto.getDepartmentId() == null) {
                    //代表用户指定科室抽取多少人 最多有一个
                    num = extraDto.getNum();
                } else {
                    newExtraDtoList.add(extraDto);
                }
            }
            Map<Long, List<ExtraDto>> deptMap = newExtraDtoList.stream().collect(Collectors.groupingBy(ExtraDto::getDepartmentId));
            for (Map.Entry<Long, List<ExtraDto>> paEntry : deptMap.entrySet()) {
                //同一科室
                Integer deptNum = null;
                List<ExtraDto> paList = paEntry.getValue();
                List<BsExtractDetailPatientEntity> existList = new ArrayList<>();
                for (ExtraDto extraDto : paList) {
                    //抽取
                    if (extraDto.getPatientId() == null) {
                        //代表用户指定科室抽取多少人 最多有一个
                        deptNum = extraDto.getNum();
                    } else {
                        BsExtractDetailPatientEntity bsExtractDetailPatient = new BsExtractDetailPatientEntity();
                        bsExtractDetailPatient.setDepartmentPatientId(extraDto.getPatientId());
                        existList.add(bsExtractDetailPatient);
                    }
                }
                ExtraDeptRestVo extraDeptRestVo = new ExtraDeptRestVo();
                extraDeptRestVo.setExistList(existList);
                extraDeptRestVo.setDepartmentId(paEntry.getKey());
                extraDeptRestVo.setHospId(entry.getKey());
                if (deptNum != null && deptNum > existList.size()) {
                    extraDeptRestVo.setNum(deptNum - existList.size());
                }
                extraDeptRestVos.add(extraDeptRestVo);
            }

            extraHospResultVo.setHospitalId(entry.getKey());
            extraHospResultVo.setDeptRestVoList(extraDeptRestVos);
            Integer deptTotalNum = 0;
            for (ExtraDeptRestVo extraDeptRestVo : extraDeptRestVos) {
                deptTotalNum += extraDeptRestVo.getExistList().size();
                if (extraDeptRestVo.getNum() != null) {
                    deptTotalNum += extraDeptRestVo.getNum();
                }
            }
            //开始处理
            if (num != null && num > deptTotalNum) {
                //用户指定了医院 选多少人
                extraHospResultVo.setNum(num - deptTotalNum);
            }
            extraHospResultVos.add(extraHospResultVo);
        }
        //开始处理吧 不好弄嘞
        //查询所有的库

        //1 所有需要补充用户的科室
        List<ExtraPatientVo> extraDeptRestVos = new ArrayList<>();
        List<Long> hospIdList = new ArrayList<>();
        List<Long> deptIdList = new ArrayList<>();
        for (ExtraHospResultVo extraHospResultVo : extraHospResultVos) {

            if (extraHospResultVo.getNum() != null) {
                hospIdList.add(extraHospResultVo.getHospitalId());
            } else {
                List<ExtraDeptRestVo> deptRestVoList = extraHospResultVo.getDeptRestVoList();
                for (ExtraDeptRestVo extraDeptRestVo : deptRestVoList) {
                    if (extraDeptRestVo.getNum() != null) {
                        deptIdList.add(extraDeptRestVo.getDepartmentId());
                    }
                }
            }
        }
        if (hospIdList.size() > 0 || deptIdList.size() > 0) {
            if (hospIdList.size() == 0) hospIdList = null;
            if (deptIdList.size() == 0) deptIdList = null;
            extraDeptRestVos = this.departmentPatientService.getAllExtraData(hospIdList, deptIdList);
        }
        //先补科室
        Map<Long, List<ExtraPatientVo>> hospMap = extraDeptRestVos.stream().collect(Collectors.groupingBy(ExtraPatientVo::getHospitalId));
        for (ExtraHospResultVo extraHospResultVo : extraHospResultVos) {
            List<ExtraPatientVo> extraPatientVos = hospMap.get(extraHospResultVo.getHospitalId());

            if (extraPatientVos != null) {
                //先把各部门已存在的移除掉
                List<ExtraDeptRestVo> deptRestVoList = extraHospResultVo.getDeptRestVoList();
                for (ExtraDeptRestVo extraDeptRestVo : deptRestVoList) {
                    List<BsExtractDetailPatientEntity> existList = extraDeptRestVo.getExistList();
                    if (existList != null) {

                        for (BsExtractDetailPatientEntity extractDetailPatientEntity : existList) {
                            MathUtil.remove(extraPatientVos, extractDetailPatientEntity.getDepartmentPatientId());
                        }
                    }
                }
                Map<Long, List<ExtraPatientVo>> deptMap = extraPatientVos.stream().collect(Collectors.groupingBy(ExtraPatientVo::getDepartmentId));

                for (ExtraDeptRestVo extraDeptRestVo : deptRestVoList) {
//                    List<BsExtractDetailPatientEntity> existList1 = extraDeptRestVo.getExistList();
//                    if(existList1 != null){
//                        for (BsExtractDetailPatientEntity extractDetailPatientEntity:existList1) {
//                            MathUtil.remove(extraPatientVos,list);
//                        }
//                    }
                    if (extraDeptRestVo.getNum() != null) {
                        List<ExtraPatientVo> list = deptMap.get(extraDeptRestVo.getDepartmentId());
//                        extraPatientVos.removeAll(list);
                        MathUtil.remove(extraPatientVos, list);
                        if (list == null || list.size() < extraDeptRestVo.getNum()) {
                            throw new RuntimeException("科室ID:" + extraDeptRestVo.getDepartmentId() + "超出住院人数");
                        }
                        Map<Long, ExtraPatientVo> collect1 = list.stream().collect(Collectors.toMap(ExtraPatientVo::getDepartmentPatientId, a -> a, (k1, k2) -> k1));
                        List<BsExtractDetailPatientEntity> existList = extraDeptRestVo.getExistList();
                        for (BsExtractDetailPatientEntity extractDetailPatientEntity : existList) {
                            collect1.remove(extractDetailPatientEntity.getDepartmentPatientId());
                        }
                        if (collect1.size() < extraDeptRestVo.getNum()) {
                            throw new RuntimeException("科室ID:" + extraDeptRestVo.getDepartmentId() + "超出住院人数");
                        }
                        Collection<ExtraPatientVo> values = collect1.values();
                        List<ExtraPatientVo> extraPatientVos1 = new ArrayList<>();
                        extraPatientVos1.addAll(values);
                        //重点
                        List<ExtraPatientVo> extraPatientVoList = MathUtil.getRandomList(extraDeptRestVo.getNum(), extraPatientVos1);
                        extraDeptRestVo.setSuppleList(extraPatientVoList);
                        //如果剩余的不再参与抽取注释这行
//                        extraPatientVos.addAll(extraPatientVos1);

                    }
                }
            }


            if (extraHospResultVo.getNum() != null) {

                if (extraPatientVos == null || extraHospResultVo.getNum() > extraPatientVos.size()) {
                    throw new RuntimeException("医院:" + extraHospResultVo.getHospitalId() + "超出住院人数");
                }
                List<ExtraPatientVo> extraPatientVoList = MathUtil.getRandomList(extraHospResultVo.getNum(), extraPatientVos);
                extraHospResultVo.setSuppleList(extraPatientVoList);
            }
        }
        //搞定 搞那个
        List<BsExtractRecordDetailEntity> detailEntityList = new ArrayList<>();
        //hosp-dept  对应列表
        Map<String, List<Long>> longIntegerHashMap = new HashMap<>();
        for (ExtraHospResultVo extraHospResultVo : extraHospResultVos) {
            List<ExtraPatientVo> suppleList = extraHospResultVo.getSuppleList();
            if (suppleList != null) {
                for (ExtraPatientVo patientVo : suppleList) {
                    supple(longIntegerHashMap, patientVo.getHospitalId(), patientVo.getDepartmentId(), patientVo.getDepartmentPatientId());
                }
            }

            List<ExtraDeptRestVo> deptRestVoList = extraHospResultVo.getDeptRestVoList();
            for (ExtraDeptRestVo extraDeptRestVo : deptRestVoList) {
                List<BsExtractDetailPatientEntity> existList = extraDeptRestVo.getExistList();
                for (BsExtractDetailPatientEntity extractDetailPatientEntity : existList) {

                    supple(longIntegerHashMap, extraHospResultVo.getHospitalId(), extraDeptRestVo.getDepartmentId(), extractDetailPatientEntity.getDepartmentPatientId());
                }
                List<ExtraPatientVo> suppleList1 = extraDeptRestVo.getSuppleList();
                if (suppleList1 != null) {
                    for (ExtraPatientVo extraPatientVo : suppleList1) {
                        supple(longIntegerHashMap, extraHospResultVo.getHospitalId(), extraDeptRestVo.getDepartmentId(), extraPatientVo.getDepartmentPatientId());
                    }
                }

            }

        }
        for (Map.Entry<String, List<Long>> entry : longIntegerHashMap.entrySet()) {
            BsExtractRecordDetailEntity bsExtractRecordDetailEntity = new BsExtractRecordDetailEntity();
            String key = entry.getKey();
            String[] split = key.split("-");
            bsExtractRecordDetailEntity.setHospitalId(Long.parseLong(split[0]));
            bsExtractRecordDetailEntity.setDepartmentId(Long.parseLong(split[1]));
            bsExtractRecordDetailEntity.setExtractNum(entry.getValue().size());
            bsExtractRecordDetailEntity.setRecordId(bsExtractRecordEntity.getExtractRecordId());
            detailEntityList.add(bsExtractRecordDetailEntity);
        }
        if (detailEntityList.size() == 0) {
            throw new RuntimeException("空");
        }
        boolean b = this.extractRecordDetailService.saveBatch(detailEntityList);
        if (!b) {
            throw new RuntimeException("保存失败");
        }
        //我不能垮  我还有好多事
        Map<String, List<Long>> result = new HashMap<>();
        for (BsExtractRecordDetailEntity extractRecordDetailEntity : detailEntityList) {
            String key = extractRecordDetailEntity.getHospitalId() + "-" + extractRecordDetailEntity.getDepartmentId();
            List<Long> longs = longIntegerHashMap.get(key);
            key = key + "-" + extractRecordDetailEntity.getExtractRecordDetail();
            result.put(key, longs);
        }
        List<BsExtractDetailPatientEntity> bsExtractDetailPatientEntities = new ArrayList<>();

        for (Map.Entry<String, List<Long>> entry : result.entrySet()) {
            String key = entry.getKey();
            String[] split = key.split("-");
            List<Long> value = entry.getValue();
            for (Long l : value) {

                BsExtractDetailPatientEntity extractDetailPatientEntity = new BsExtractDetailPatientEntity();
                extractDetailPatientEntity.setDetailId(Long.parseLong(split[2]));
                extractDetailPatientEntity.setDepartmentPatientId(l);
                bsExtractDetailPatientEntities.add(extractDetailPatientEntity);
            }
        }
        suppleExtra(bsExtractDetailPatientEntities, detailEntityList, bsExtractRecordEntity);

        return null;
    }

    private void suppleExtra(List<BsExtractDetailPatientEntity> bsExtractDetailPatientEntities, List<BsExtractRecordDetailEntity> detailEntityList, BsExtractRecordEntity bsExtractRecordEntity) {

        Set<Long> collect = bsExtractDetailPatientEntities.stream().map(BsExtractDetailPatientEntity::getDepartmentPatientId).collect(Collectors.toSet());
        QueryWrapper<BsDepartmentPatientImgEntity> imgEntityQueryWrapper = new QueryWrapper<>();
        imgEntityQueryWrapper.in("department_patient_id", collect);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        imgEntityQueryWrapper.likeRight("create_time", sdf.format(new Date()));
        imgEntityQueryWrapper.isNull("extract_detail_patient_id");
        imgEntityQueryWrapper.ne("img_type", 1);
        List<BsDepartmentPatientImgEntity> list = this.patientImgService.list(imgEntityQueryWrapper);
        Map<Long, List<BsDepartmentPatientImgEntity>> imgMap = list.stream().collect(Collectors.groupingBy(BsDepartmentPatientImgEntity::getDepartmentPatientId));

        List<BsDepartmentPatientImgEntity> updateList = new ArrayList<>();
        Map<Long, CountPatientVo> patientDoneMap = new HashMap<>();
        for (BsExtractDetailPatientEntity patientEntity : bsExtractDetailPatientEntities) {
            List<BsDepartmentPatientImgEntity> bsDepartmentPatientImgEntities = imgMap.get(patientEntity.getDepartmentPatientId());
            if (bsDepartmentPatientImgEntities != null && bsDepartmentPatientImgEntities.size() > 0) {
                patientEntity.setIsDone(1);
//                updateList.addAll(bsDepartmentPatientImgEntities);
                CountPatientVo countPatientVo = patientDoneMap.get(patientEntity.getDetailId());
                if (countPatientVo != null) {
                    countPatientVo.setDonePatientCount(countPatientVo.getDonePatientCount() + 1);
                } else {
                    countPatientVo = new CountPatientVo();
                    countPatientVo.setTotalPatientCount(bsDepartmentPatientImgEntities.size());
                    countPatientVo.setDonePatientCount(1);
                    patientDoneMap.put(patientEntity.getDetailId(), countPatientVo);
                }
            } else {
                patientEntity.setIsDone(0);
            }
        }

        Map<Long, BsExtractRecordDetailEntity> detailMap = detailEntityList.stream().collect(Collectors.toMap(BsExtractRecordDetailEntity::getExtractRecordDetail, Function.identity(), (key1, key2) -> key2));

        int num = 0;
        List<BsExtractRecordDetailEntity> updateDetails = new ArrayList<>();
        for (Map.Entry<Long, CountPatientVo> entry : patientDoneMap.entrySet()) {
            CountPatientVo value = entry.getValue();
            if (value.getDonePatientCount() == value.getTotalPatientCount()) {
                BsExtractRecordDetailEntity bsExtractRecordDetailEntity = detailMap.get(entry.getKey());
                bsExtractRecordDetailEntity.setIsDone(1);
                num++;
                updateDetails.add(bsExtractRecordDetailEntity);
            }
        }
        if (updateDetails.size() > 0) {
            boolean b = this.extractRecordDetailService.updateBatchById(updateDetails);
            if (!b) {
                throw new RuntimeException("详情更新失败");
            }
            if (num == updateDetails.size()) {
                bsExtractRecordEntity.setIsDone(1);
                boolean b1 = this.extractRecordService.updateById(bsExtractRecordEntity);
                if (!b1) {
                    throw new RuntimeException("记录更新失败");
                }
            }
        }
        boolean b1 = this.extractDetailPatientService.saveBatch(bsExtractDetailPatientEntities);
        if (!b1) {
            throw new RuntimeException("失败");
        }
        for (BsExtractDetailPatientEntity patientEntity : bsExtractDetailPatientEntities) {
            if (patientEntity.getIsDone() == 1) {
                List<BsDepartmentPatientImgEntity> bsDepartmentPatientImgEntities = imgMap.get(patientEntity.getDepartmentPatientId());
                if (bsDepartmentPatientImgEntities != null) {
                    for (BsDepartmentPatientImgEntity departmentPatientImgEntity : bsDepartmentPatientImgEntities) {
                        departmentPatientImgEntity.setExtractDetailPatientId(patientEntity.getExtractDetailPatientId());
                        updateList.add(departmentPatientImgEntity);
                    }
                }
            }
        }
        if (updateList.size() > 0) {

            boolean b = this.patientImgService.updateBatchById(updateList);
            if (!b) {
                throw new RuntimeException("更新图片失败");
            }
        }
    }

    @Override
    @Transactional
    public void randomExtra(Integer extraNumber) {
        if (extraNumber <= 0) {
            throw new RuntimeException("抽取人数不合法");
        }
        BsExtractRecordEntity bsExtractRecordEntity = new BsExtractRecordEntity();
        bsExtractRecordEntity.setExtractType(1);
        bsExtractRecordEntity.setIsDone(0);
        boolean save = this.extractRecordService.save(bsExtractRecordEntity);
        if (!save) {
            throw new RuntimeException("抽取记录保存失败");
        }

        List<ExtraPatientVo> extraDeptRestVos = this.departmentPatientService.getAllHospData();
        if (extraNumber > extraDeptRestVos.size()) {
            throw new RuntimeException("抽取人数大于在住院人数");
        }
        List<ExtraPatientVo> extraPatientVoList = MathUtil.getRandomList(extraNumber, extraDeptRestVos);

        extraResult(bsExtractRecordEntity, extraPatientVoList);
    }

    @Override
    @Transactional
    public void savePatient(PatientDto patientDto) {



        BsPatientEntity bsPatientEntity = new BsPatientEntity();
        BeanUtil.copyProperties(patientDto, bsPatientEntity);
        boolean save = this.save(bsPatientEntity);
        if (!save) {
            throw new RRException("信息保存失败");
        }

        BsDepartmentPatientEntity departmentPatientEntity = new BsDepartmentPatientEntity();
        BeanUtil.copyProperties(patientDto, departmentPatientEntity);
        departmentPatientEntity.setPatientId(bsPatientEntity.getPatientId());
        departmentPatientEntity.setIsLeave(0);
        departmentPatientEntity.setWardNumber(patientDto.getWardNumber());
        departmentPatientEntity.setBedNumber(patientDto.getBedNumber());
        Long departmentId = departmentPatientEntity.getDepartmentId();
        if (departmentId == null) {
            throw new RRException("请选择科室");
        }
        BsDepartmentEntity byId = this.departmentService.getById(departmentId);
        if (byId == null) {
            throw new RRException("科室不存在");
        }
        boolean departmentSave = this.departmentPatientService.save(departmentPatientEntity);
        if (!departmentSave) {
            throw new RRException("住院信息保存失败");
        }

        List<BsDepartmentPatientImgEntity> patientImgEntityList = new ArrayList<>();
        String patientImg = patientDto.getPatientImg();
        if (StringUtils.isNotBlank(patientImg)) {
            BsDepartmentPatientImgEntity bsDepartmentPatientImgEntity = new BsDepartmentPatientImgEntity();
            bsDepartmentPatientImgEntity.setPatientImg(GetUrlPic.saveImg(patientImg,filePath));
            patientImgEntityList.add(bsDepartmentPatientImgEntity);
        }

        if (patientDto.getPatientImgEntityList() != null && patientDto.getPatientImgEntityList().size() > 0) {
            patientImgEntityList.addAll(patientDto.getPatientImgEntityList());
        }
        if(patientImgEntityList.size() > 0){
            for (BsDepartmentPatientImgEntity imgEntity : patientImgEntityList) {
                imgEntity.setDepartmentPatientId(departmentPatientEntity.getDepartmentPatientId());
                imgEntity.setPhotographDate(new Date());
                imgEntity.setExtractDetailPatientId(null);
                imgEntity.setImgType(1);
            }
            boolean b = this.patientImgService.saveBatch(patientImgEntityList);
            if (!b) {
                throw new RRException("入院照片保存失败");
            }
        }
    }

    @Override
    public LookDetailVo getDetailData(Long extractDetailPatientId) {

        LookDetailVo lookDetailVo = new LookDetailVo();
        BsExtractDetailPatientEntity extractDetailPatientEntity = this.extractDetailPatientService.getById(extractDetailPatientId);
        Long departmentPatientId = extractDetailPatientEntity.getDepartmentPatientId();
        BsDepartmentPatientEntity departmentPatientEntity = this.departmentPatientService.getById(departmentPatientId);
        Long patientId = departmentPatientEntity.getPatientId();
        BsPatientEntity patientEntity = this.patientService.getById(patientId);
        Long departmentId = departmentPatientEntity.getDepartmentId();
        BsDepartmentEntity departmentEntity = this.departmentService.getById(departmentId);
        Long hospitalId = departmentEntity.getHospitalId();
        BsHospitalEntity hospitalEntity = this.hospitalService.getById(hospitalId);
        QueryWrapper<BsDepartmentPatientImgEntity> imgEntityQueryWrapper = new QueryWrapper<>();
        imgEntityQueryWrapper.eq("department_patient_id", departmentPatientId);
        List<BsDepartmentPatientImgEntity> imgEntityList = this.patientImgService.list(imgEntityQueryWrapper);

        lookDetailVo.setHospitalName(hospitalEntity.getHospitalName());
        lookDetailVo.setDepartmentName(departmentEntity.getDepartmentName());
        lookDetailVo.setPatientName(patientEntity.getPatientName());
        lookDetailVo.setWardNumber(departmentPatientEntity.getWardNumber());
        lookDetailVo.setBedNumber(departmentPatientEntity.getBedNumber());

        List<LookDetailListVo> hospitalizationPictures = new ArrayList<>();
        List<LookDetailListVo> thisRecords = new ArrayList<>();
        List<LookDetailListVo> historyRecords = new ArrayList<>();
        for (BsDepartmentPatientImgEntity departmentPatientImgEntity : imgEntityList) {
            if(departmentPatientImgEntity.getImgType() == 2){
                LookDetailListVo lookDetailListVo = new LookDetailListVo();
                lookDetailListVo.setImgUrl(departmentPatientImgEntity.getPatientImg());
                lookDetailListVo.setTime(departmentPatientImgEntity.getPhotographDate());
                historyRecords.add(lookDetailListVo);
            }
            if (departmentPatientImgEntity.getExtractDetailPatientId() != null && departmentPatientImgEntity.getExtractDetailPatientId().intValue() == extractDetailPatientId) {
                LookDetailListVo thisLookDetailListVo = new LookDetailListVo();
                thisLookDetailListVo.setImgUrl(departmentPatientImgEntity.getPatientImg());
                thisLookDetailListVo.setTime(departmentPatientEntity.getHospitalizationDate());
                thisRecords.add(thisLookDetailListVo);
            }
            if (departmentPatientImgEntity.getImgType() == 1) {
                LookDetailListVo thisLookDetailListVo = new LookDetailListVo();
                thisLookDetailListVo.setImgUrl(departmentPatientImgEntity.getPatientImg());
                thisLookDetailListVo.setTime(departmentPatientEntity.getHospitalizationDate());
                hospitalizationPictures.add(thisLookDetailListVo);
            }
        }
        lookDetailVo.setHistoryRecords(historyRecords);
        lookDetailVo.setThisRecords(thisRecords);
        lookDetailVo.setHospitalizationPictures(hospitalizationPictures);
        return lookDetailVo;
    }

    @Override
    public void dischargeRegistration(DischargeRegistrationDto patientDto) {

        Long departmentPatientId = patientDto.getDepartmentPatientId();
        BsDepartmentPatientEntity departmentPatientEntity = this.departmentPatientService.getById(departmentPatientId);
        if (departmentPatientEntity == null) {
            throw new RRException("未找到患者");
        }
        if (departmentPatientEntity.getIsLeave() == 1) {
            throw new RRException("患者已出院");
        }
        if (patientDto.getLeaveHospitalDate() == null) {
            throw new RRException("请选择出院日期");
        }
        //未完成  department_patient_id
        QueryWrapper<BsExtractDetailPatientEntity> extractDetailPatientEntityQueryWrapper = new QueryWrapper<>();
        extractDetailPatientEntityQueryWrapper.eq("department_patient_id", departmentPatientEntity.getDepartmentPatientId());
        extractDetailPatientEntityQueryWrapper.eq("is_done", 0);
        List<BsExtractDetailPatientEntity> list = this.extractDetailPatientService.list(extractDetailPatientEntityQueryWrapper);
        if (list.size() > 0) {
            throw new RRException("该患者已被抽查，请先拍照上报");
        }
        departmentPatientEntity.setIsLeave(1);
        departmentPatientEntity.setLeaveHospitalDate(patientDto.getLeaveHospitalDate());
        this.departmentPatientService.updateById(departmentPatientEntity);

    }

    @Override
    public BsDepartmentPatientVo getModelById(Long departmentPatientId) {
        BsDepartmentPatientVo departmentPatientVo = new BsDepartmentPatientVo();
        BsDepartmentPatientEntity departmentPatientEntity = this.departmentPatientService.getById(departmentPatientId);
        BsPatientEntity patientEntity = this.getById(departmentPatientEntity.getPatientId());
        BeanUtil.copyProperties(departmentPatientEntity, departmentPatientVo);
        BeanUtil.copyProperties(departmentPatientVo, patientEntity, "remark");
        QueryWrapper<BsDepartmentPatientImgEntity> imgEntityQueryWrapper = new QueryWrapper<>();
        imgEntityQueryWrapper.eq("department_patient_id", departmentPatientEntity.getDepartmentPatientId());
        imgEntityQueryWrapper.eq("img_type", 1);
        List<BsDepartmentPatientImgEntity> list = this.patientImgService.list(imgEntityQueryWrapper);
        departmentPatientVo.setImgEntities(list);
        return departmentPatientVo;
    }

    @Override
    @Transactional
    public void updateModelById(BsDepartmentPatientPageVo departmentPatientVo) {

        BsDepartmentPatientEntity departmentPatientEntity = this.departmentPatientService.getById(departmentPatientVo.getDepartmentPatientId());
        if (departmentPatientEntity == null) {
            throw new RRException("科室患者不存在");
        }
        QueryWrapper<BsDepartmentPatientImgEntity> imgEntityQueryWrapper = new QueryWrapper<>();
        imgEntityQueryWrapper.eq("department_patient_id", departmentPatientEntity.getDepartmentPatientId());
        imgEntityQueryWrapper.eq("img_type", 1);
        List<BsDepartmentPatientImgEntity> list = this.patientImgService.list(imgEntityQueryWrapper);
        for (BsDepartmentPatientImgEntity bsDepartmentPatientImgEntity : list) {
            boolean b = DeleteFileUtil.deleteFile(filePath + bsDepartmentPatientImgEntity.getPatientImg());
            if (!b) {
                throw new RRException("删除旧文件失败");
            }
        }
        this.patientImgService.remove(imgEntityQueryWrapper);
        BeanUtil.copyProperties(departmentPatientVo, departmentPatientEntity, "patientId");
        BsPatientEntity patientEntity = this.getById(departmentPatientEntity.getPatientId());
        BeanUtil.copyProperties(departmentPatientVo, patientEntity, "remark", "patientId");
        this.updateById(patientEntity);
        BeanUtil.copyProperties(departmentPatientVo, departmentPatientEntity);
        departmentPatientEntity.setPatientId(patientEntity.getPatientId());
        this.departmentPatientService.updateById(departmentPatientEntity);
//        this.patientService.removeById(departmentPatientVo.getPatientId());
        String hospitalizedImg = departmentPatientVo.getHospitalizedImg();
        if (StringUtils.isNotBlank(hospitalizedImg)) {
//            for (BsDepartmentPatientImgEntity imgEntity:imgEntities) {
            BsDepartmentPatientImgEntity imgEntity = new BsDepartmentPatientImgEntity();
            imgEntity.setDepartmentPatientId(departmentPatientVo.getDepartmentPatientId());
            imgEntity.setImgType(1);
            imgEntity.setExtractDetailPatientId(null);
            imgEntity.setPatientImg(hospitalizedImg);
            imgEntity.setPhotographDate(new Date());
            imgEntity.setDepartmentPatientId(departmentPatientVo.getDepartmentPatientId());
//            }
            this.patientImgService.save(imgEntity);
        }
    }

    @Override
    @Transactional
    public void wardRoundReport(WardRoundReportDto wardRoundReportDto) {

        List<BsDepartmentPatientImgEntity> patientImgEntities = wardRoundReportDto.getPatientImgEntities();
        if (patientImgEntities == null || patientImgEntities.size() == 0) {
            throw new RRException("请上传图片");
        }


        Long extractDetailPatientId = wardRoundReportDto.getExtractDetailPatientId();

        BsExtractDetailPatientEntity extractDetailPatientEntity = this.extractDetailPatientService.getById(extractDetailPatientId);
        if (extractDetailPatientEntity == null) {
            throw new RRException("未找到抽取记录");
        }

        extractDetailPatientEntity.setIsDone(1);
        this.extractDetailPatientService.updateById(extractDetailPatientEntity);
        QueryWrapper<BsExtractDetailPatientEntity> detailPatientEntityQueryWrapper = new QueryWrapper<>();
        detailPatientEntityQueryWrapper.in("detail_id", extractDetailPatientEntity.getDetailId());
        List<BsExtractDetailPatientEntity> list = this.extractDetailPatientService.list(detailPatientEntityQueryWrapper);
        int m = 0;
        for (BsExtractDetailPatientEntity extractDetailPatientEntityDb : list) {
            if (extractDetailPatientEntityDb.getIsDone() == 1) {
                m++;
            }
        }
        if (m == list.size()) {
            BsExtractRecordDetailEntity recordDetailEntity = this.extractRecordDetailService.getById(extractDetailPatientEntity.getDetailId());
            recordDetailEntity.setIsDone(1);
            this.extractRecordDetailService.updateById(recordDetailEntity);
            QueryWrapper<BsExtractRecordDetailEntity> extractRecordEntityQueryWrapper = new QueryWrapper<>();
            extractRecordEntityQueryWrapper.eq("record_id", recordDetailEntity.getRecordId());
            List<BsExtractRecordDetailEntity> recordEntityList = this.extractRecordDetailService.list(extractRecordEntityQueryWrapper);
            int n = 0;
            for (BsExtractRecordDetailEntity bsExtractRecordDetailEntity : recordEntityList) {
                if (bsExtractRecordDetailEntity.getIsDone() == 1) {
                    n++;
                }
            }
            if (n == recordEntityList.size()) {
                BsExtractRecordEntity bsExtractRecordEntity = this.extractRecordService.getById(recordDetailEntity.getRecordId());
                bsExtractRecordEntity.setIsDone(1);
                this.extractRecordService.updateById(bsExtractRecordEntity);
            }
        }


        for (BsDepartmentPatientImgEntity departmentPatientImgEntity : patientImgEntities) {
            departmentPatientImgEntity.setDepartmentPatientId(extractDetailPatientEntity.getDepartmentPatientId());
            departmentPatientImgEntity.setPhotographDate(new Date());
            departmentPatientImgEntity.setExtractDetailPatientId(wardRoundReportDto.getExtractDetailPatientId());
            departmentPatientImgEntity.setImgType(2);
        }

        this.patientImgService.saveBatch(patientImgEntities);

    }

    @Override
    public AllReportVo getReportList(Long departmentId) {

        AllReportVo allReportVo = new AllReportVo();
        List<ReportVo> reportList = this.baseMapper.getReportList(departmentId);
        allReportVo.setReportList(reportList);
        List<ReportVo> doneReportList = this.baseMapper.getDoneReportList(departmentId);
        allReportVo.setDoneReportList(doneReportList);
        return allReportVo;
    }

    @Override
    public Integer countByIdNumber(String idNumber) {
        return this.baseMapper.countByIdNumber(idNumber);
    }

    private void extraResult(BsExtractRecordEntity bsExtractRecordEntity, List<ExtraPatientVo> extraPatientVoList) {
        Map<String, List<Long>> longIntegerHashMap = new HashMap<>();
        for (ExtraPatientVo extraPatientVo : extraPatientVoList) {
            supple(longIntegerHashMap, extraPatientVo.getHospitalId(), extraPatientVo.getDepartmentId(), extraPatientVo.getDepartmentPatientId());

        }

        List<BsExtractRecordDetailEntity> detailEntityList = new ArrayList<>();
        for (Map.Entry<String, List<Long>> entry : longIntegerHashMap.entrySet()) {
            BsExtractRecordDetailEntity bsExtractRecordDetailEntity = new BsExtractRecordDetailEntity();
            String key = entry.getKey();
            String[] split = key.split("-");
            bsExtractRecordDetailEntity.setHospitalId(Long.parseLong(split[0]));
            bsExtractRecordDetailEntity.setDepartmentId(Long.parseLong(split[1]));
            bsExtractRecordDetailEntity.setExtractNum(entry.getValue().size());
            bsExtractRecordDetailEntity.setRecordId(bsExtractRecordEntity.getExtractRecordId());
            detailEntityList.add(bsExtractRecordDetailEntity);
        }
        if (detailEntityList.size() == 0) {
            throw new RuntimeException("空");
        }
        boolean b = this.extractRecordDetailService.saveBatch(detailEntityList);
        if (!b) {
            throw new RuntimeException("保存失败");
        }
        //我不能垮  我还有好多事
        Map<String, List<Long>> result = new HashMap<>();
        for (BsExtractRecordDetailEntity extractRecordDetailEntity : detailEntityList) {
            String key = extractRecordDetailEntity.getHospitalId() + "-" + extractRecordDetailEntity.getDepartmentId();
            List<Long> longs = longIntegerHashMap.get(key);
            key = key + "-" + extractRecordDetailEntity.getExtractRecordDetail();
            result.put(key, longs);
        }
        List<BsExtractDetailPatientEntity> bsExtractDetailPatientEntities = new ArrayList<>();
        for (Map.Entry<String, List<Long>> entry : result.entrySet()) {
            String key = entry.getKey();
            String[] split = key.split("-");
            List<Long> value = entry.getValue();
            for (Long l : value) {

                BsExtractDetailPatientEntity extractDetailPatientEntity = new BsExtractDetailPatientEntity();
                extractDetailPatientEntity.setDetailId(Long.parseLong(split[2]));
                extractDetailPatientEntity.setDepartmentPatientId(l);
                bsExtractDetailPatientEntities.add(extractDetailPatientEntity);
            }
        }
        suppleExtra(bsExtractDetailPatientEntities, detailEntityList, bsExtractRecordEntity);
    }

    private void supple(Map<String, List<Long>> longIntegerHashMap, Long hospitalId, Long departmentId, Long departmentPatientId) {
        String key = hospitalId + "-" + departmentId;
        if (longIntegerHashMap.containsKey(key)) {
            List<Long> longs = longIntegerHashMap.get(key);
            longs.add(departmentPatientId);
        } else {
            List<Long> longs = new ArrayList<>();
            longs.add(departmentPatientId);
            longIntegerHashMap.put(key, longs);
        }
    }

}